package com.ht.web360.base.feignApi;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.*;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.ht.web360.base.utils.exceptions.MessageException;
import com.ht.web360.base.utils.exceptions.OssException;
import lombok.Data;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Component
@Data
public class OssImpl implements Oss {
    private final DiscoveryClient discoveryClient;

    public OssImpl(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    private String getOssUrl() {
        List<ServiceInstance> instances = discoveryClient.getInstances("oss-server");
        int i = RandomUtil.randomInt(instances.size());
        ServiceInstance instance = instances.get(i);
        return instance.getHost() + ":" + instance.getPort() + "/";
    }

    @Override
    public String upload(MultipartFile file) {
        HttpRequest post = HttpUtil.createPost(this.getOssUrl());
        post.contentType(ContentType.MULTIPART.getValue());
        post.form("file", file);
        return doUpload(post);
    }
    
    @Override
    public String upload(byte[] data) {
        HttpRequest post = HttpUtil.createPost(this.getOssUrl());
        post.contentType(ContentType.MULTIPART.getValue());
        post.form("file", data, "file");
        return doUpload(post);
    }

    private String doUpload(HttpRequest post) {
        try (
                HttpResponse response = post.execute();
        ) {
            JSON parse = JSONUtil.parse(response.body());
            Object success = parse.getByPath("status");
            if (success instanceof Boolean su) {
                if (su) {
                    return parse.getByPath("data").toString();
                }
            }
            throw new Exception();
        } catch (Exception e) {
            throw new OssException();
        }
    }

    @Override
    public InputStream download(String md5) {
        HttpRequest get = HttpUtil.createGet(this.getOssUrl() + md5);
        InputStream is;
        try (HttpResponse response = get.execute()) {
            is = response.bodyStream();
            return is;
        }
    }

    @Override
    public void delete(String md5) {
        if (md5 == null) {
            return;
        }
        HttpRequest get = HttpUtil.createGet(this.getOssUrl() + md5);
        get.method(Method.DELETE);
        try (
                HttpResponse response = get.execute()
        ) {
            JSON json = JSONUtil.parse(response.body());
            if (!(Boolean) json.getByPath("status")) {
                throw new MessageException("删除失败，请稍后重试");
            }
        }
    }
}


